// 全局变量
let carList = [];

// 推荐图书数据
const recommendedBooks = [
    {
        id: 1,
        title: "棕色的熊，你在看什么？",
        image: "./img/tupian32.jpg",
        price: 18,
        condition: "九成新",
        age: "0-2岁"
    },
    {
        id: 2,
        title: "好饿的毛毛虫",
        image: "./img/tupian33.jpg",
        price: 16,
        condition: "八成新",
        age: "0-2岁"
    },
    {
        id: 3,
        title: "大卫上学去",
        image: "./img/tupian34.jpg",
        price: 16,
        condition: "八成新",
        age: "3-4岁"
    },
    {
        id: 4,
        title: "猜猜我有多爱你",
        image: "./img/tupian35.jpg",
        price: 16,
        condition: "八成新",
        age: "3-4岁"
    },
    {
        id: 5,
        title: "爷爷一定有办法",
        image: "./img/tupian36.jpg",
        price: 16,
        condition: "八成新",
        age: "3-4岁"
    },
    {
        id: 6,
        title: "谁藏起来了",
        image: "./img/tupian37.jpg",
        price: 18,
        condition: "九成新",
        age: "3-4岁"
    },
    {
        id: 7,
        title: "云朵面包",
        image: "./img/tupian38.jpg",
        price: 18,
        condition: "九成新",
        age: "3-4岁"
    },
    {
        id: 8,
        title: "遇见古埃及人",
        image: "./img/tupian39.jpg",
        price: 18,
        condition: "九成新",
        age: "5-6岁"
    },
    {
        id: 9,
        title: "爱心树",
        image: "./img/tupian40.jpg",
        price: 16,
        condition: "八成新",
        age: "5-6岁"
    },
    {
        id: 10,
        title: "阿罗系列绘本",
        image: "./img/tupian41.jpg",
        price: 18,
        condition: "九成新",
        age: "5-6岁"
    }
];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    
    // 加载购物车数据
    initPage();
    
    // 绑定事件
    bindEvents();
});

// 初始化页面
function initPage() {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，显示空购物车
        checkEmptyCart();
        loadRecommendedBooks();
        return;
    }
    
    // 已登录，加载购物车数据
    loadCartData();
    loadRecommendedBooks();
}

// 从后端加载购物车数据
function loadCartData() {
    // 显示加载中
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        ApiService.cart.getCart()
            .then(response => {
                layer.close(loadingIndex);
                const items = response.data;
                if (Array.isArray(items) && items.length > 0) {
                    carList = items.map(item => ({
                        id: item.id,
                        book: {
                            id: item.bookId,
                            title: item.bookTitle,
                            author: item.bookAuthor,
                            price: item.price,
                            image: item.imageUrl || `./img/tupian${Math.floor(Math.random() * 20) + 1}.jpg`
                        },
                        quantity: item.quantity,
                        subtotal: item.price * item.quantity
                    }));
                    
                    renderCart();
                    updateTotalInfo();
                } else {
                    carList = [];
                    checkEmptyCart();
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取购物车数据失败:", error);
                layer.msg('获取购物车数据失败，请重试', {icon: 2});
                checkEmptyCart();
            });
    });
}

// 渲染购物车
function renderCart() {
    const carListContent = document.getElementById('carList');
    if (!carListContent) return;

    if (carList.length === 0) {
        checkEmptyCart();
        return;
    }

    carListContent.innerHTML = carList.map(item => `
        <tr id="${item.id}" class="cart-item">
            <td>
                <input type="checkbox" class="item-select" value="${item.id}" lay-skin="primary">
            </td>
            <td>
                <div class="item-info">
                    <div class="item-image">
                        <img src="${item.book.image}" alt="${item.book.title}">
                    </div>
                    <div class="item-details">
                        <h3 class="item-title">
                            <a href="detail.html?id=${item.book.id}">${item.book.title}</a>
                        </h3>
                        <p class="item-attrs">${item.book.author || '未知作者'}</p>
                    </div>
                </div>
            </td>
            <td>
                <span class="item-price">¥${item.book.price.toFixed(2)}</span>
            </td>
            <td>
                <div class="quantity-control">
                    <button class="quantity-btn minus" onclick="decreaseQuantity(${item.id})">-</button>
                    <input type="number" class="quantity-input" value="${item.quantity}" min="1" max="99" onchange="updateQuantity(${item.id}, this.value)">
                    <button class="quantity-btn plus" onclick="increaseQuantity(${item.id})">+</button>
                </div>
            </td>
            <td>
                <span class="item-subtotal">¥${item.subtotal.toFixed(2)}</span>
            </td>
            <td>
                <button class="layui-btn layui-btn-xs layui-btn-danger delete-btn" onclick="deleteItem(${item.id})">删除</button>
            </td>
        </tr>
    `).join('');

    checkEmptyCart();
    
    // 初始化layui表单元素
    layui.use('form', function(){
        var form = layui.form;
        form.render();
    });
}

// 增加商品数量
function increaseQuantity(id) {
    const item = carList.find(item => item.id === id);
    if (!item) return;

    if (item.quantity < 99) {
        item.quantity++;
        updateCartItemQuantity(id, item.quantity);
    }
}

// 减少商品数量
function decreaseQuantity(id) {
    const item = carList.find(item => item.id === id);
    if (!item) return;

    if (item.quantity > 1) {
        item.quantity--;
        updateCartItemQuantity(id, item.quantity);
    }
}

// 直接更新数量
function updateQuantity(id, value) {
    const item = carList.find(item => item.id === id);
    if (!item) return;

    // 确保数量在1-99之间
    value = Math.max(1, Math.min(99, parseInt(value) || 1));
    updateCartItemQuantity(id, value);
}

// 更新购物车项目数量（调用API）
function updateCartItemQuantity(id, quantity) {
    const item = carList.find(item => item.id === id);
    if (!item) return;
    
    // 显示加载中
    layui.use('layer', function() {
        const layer = layui.layer;
        
        ApiService.cart.updateCartItem(id, quantity)
            .then(response => {
                if (response.data) {
                    // 更新本地数据
                    item.quantity = quantity;
                    item.subtotal = item.book.price * item.quantity;
                    updateItemDisplay(id);
                    updateTotalInfo();
                    
                    // 更新头部购物车数量
                    if (AuthService.updateCartCount) {
                        AuthService.updateCartCount();
                    }
                }
            })
            .catch(error => {
                console.error("更新购物车失败:", error);
                layer.msg('更新购物车失败，请重试', {icon: 2});
                // 恢复原来的数量
                loadCartData();
            });
    });
}

// 更新商品显示
function updateItemDisplay(id) {
    const tr = document.getElementById(id);
    const item = carList.find(item => item.id === id);
    if (!tr || !item) return;

    tr.querySelector('.quantity-input').value = item.quantity;
    tr.querySelector('.item-subtotal').textContent = `¥${item.subtotal.toFixed(2)}`;
}

// 删除商品
function deleteItem(id) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确定要删除这个商品吗？', {icon: 3, title:'提示'}, function(index){
            ApiService.cart.removeCartItem(id)
                .then(response => {
                    if (response.data || response.status === 200) {
                        // 从本地数据中删除
                        carList = carList.filter(item => item.id !== id);
                        const element = document.getElementById(id);
                        if (element) {
                            element.remove();
                        }
                        updateTotalInfo();
                        checkEmptyCart();
                        
                        // 更新头部购物车数量
                        if (AuthService.updateCartCount) {
                            AuthService.updateCartCount();
                        }
                        
                        layer.msg('删除成功', {icon: 1});
                    }
                })
                .catch(error => {
                    console.error("删除商品失败:", error);
                    layer.msg('删除商品失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 更新总计信息
function updateTotalInfo() {
    const selectedItems = Array.from(document.querySelectorAll('.item-select:checked'))
        .map(checkbox => carList.find(item => item.id === parseInt(checkbox.value)))
        .filter(Boolean);

    const totalCount = selectedItems.length;
    const totalPrice = selectedItems.reduce((sum, item) => sum + item.subtotal, 0);

    // 更新选中数量和总价
    const selectedCountElement = document.querySelector('.selected-count');
    const totalPriceElement = document.querySelector('.total-price');
    const checkoutBtn = document.querySelector('.checkout-btn');

    if (selectedCountElement) selectedCountElement.textContent = totalCount;
    if (totalPriceElement) totalPriceElement.textContent = `￥${totalPrice.toFixed(2)}`;
    if (checkoutBtn) checkoutBtn.disabled = totalCount === 0;
}

// 绑定事件
function bindEvents() {
    // 全选按钮
    const selectAllCheckboxes = document.querySelectorAll('#selectAll, #selectAllBottom');
    selectAllCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', handleSelectAll);
    });

    // 商品选择
    document.addEventListener('change', e => {
        if (e.target.classList.contains('item-select')) {
            updateSelectAll();
            updateTotalInfo();
        }
    });

    // 删除选中商品按钮
    const deleteSelectedBtn = document.querySelector('.delete-selected');
    if (deleteSelectedBtn) {
        deleteSelectedBtn.addEventListener('click', deleteSelected);
    }
    
    // 结算按钮
    const checkoutBtn = document.querySelector('.checkout-btn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', checkout);
    }
    
    // 清空购物车按钮
    const clearCartBtn = document.querySelector('.clear-cart');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', clearCart);
    }
}

// 全选/取消全选
function handleSelectAll(e) {
    const isChecked = e.target.checked;
    document.querySelectorAll('.item-select').forEach(checkbox => {
        checkbox.checked = isChecked;
    });
    document.querySelectorAll('#selectAll, #selectAllBottom').forEach(checkbox => {
        checkbox.checked = isChecked;
    });
    updateTotalInfo();
}

// 更新全选状态
function updateSelectAll() {
    const total = document.querySelectorAll('.item-select').length;
    const selected = document.querySelectorAll('.item-select:checked').length;
    const isAllSelected = total === selected && total > 0;
    
    document.querySelectorAll('#selectAll, #selectAllBottom').forEach(checkbox => {
        checkbox.checked = isAllSelected;
    });
}

// 删除选中商品
function deleteSelected() {
    const selectedIds = Array.from(document.querySelectorAll('.item-select:checked'))
        .map(checkbox => parseInt(checkbox.value));

    if (selectedIds.length === 0) {
        layui.use('layer', function() {
            const layer = layui.layer;
            layer.msg('请选择要删除的商品', {icon: 0});
        });
        return;
    }

    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm(`确定要删除选中的 ${selectedIds.length} 个商品吗？`, {icon: 3, title:'提示'}, function(index){
            // 创建一个Promise数组，每个Promise代表一个删除操作
            const deletePromises = selectedIds.map(id => 
                ApiService.cart.removeCartItem(id)
                    .then(() => id)
                    .catch(error => {
                        console.error(`删除商品 ${id} 失败:`, error);
                        return null;
                    })
            );
            
            // 等待所有删除操作完成
            Promise.all(deletePromises)
                .then(results => {
                    // 过滤出成功删除的ID
                    const successIds = results.filter(id => id !== null);
                    
                    if (successIds.length > 0) {
                        // 从本地数据中删除
                        successIds.forEach(id => {
                            carList = carList.filter(item => item.id !== id);
                            const element = document.getElementById(id);
                            if (element) {
                                element.remove();
                            }
                        });
                        
                        updateTotalInfo();
                        checkEmptyCart();
                        
                        // 更新头部购物车数量
                        if (AuthService.updateCartCount) {
                            AuthService.updateCartCount();
                        }
                        
                        layer.msg(`成功删除 ${successIds.length} 个商品`, {icon: 1});
                    } else {
                        layer.msg('删除失败，请重试', {icon: 2});
                    }
                });
            
            layer.close(index);
        });
    });
}

// 清空购物车
function clearCart() {
    if (carList.length === 0) {
        layui.use('layer', function() {
            const layer = layui.layer;
            layer.msg('购物车已经是空的', {icon: 0});
        });
        return;
    }
    
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确定要清空购物车吗？', {icon: 3, title:'提示'}, function(index){
            ApiService.cart.clearCart()
                .then(response => {
                    if (response.data || response.status === 200) {
                        // 清空本地数据
                        carList = [];
                        renderCart();
                        updateTotalInfo();
                        checkEmptyCart();
                        
                        // 更新头部购物车数量
                        if (AuthService.updateCartCount) {
                            AuthService.updateCartCount();
                        }
                        
                        layer.msg('购物车已清空', {icon: 1});
                    }
                })
                .catch(error => {
                    console.error("清空购物车失败:", error);
                    layer.msg('清空购物车失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 结算功能
function checkout() {
    const selectedIds = Array.from(document.querySelectorAll('.item-select:checked'))
        .map(checkbox => parseInt(checkbox.value));
    
    if (selectedIds.length === 0) {
        layui.use('layer', function() {
            const layer = layui.layer;
            layer.msg('请选择要结算的商品', {icon: 0});
        });
        return;
    }
    
    // 获取选中的商品
    const selectedItems = selectedIds.map(id => carList.find(item => item.id === id))
        .filter(Boolean);
    
    // 将选中的商品信息存储到本地存储中
    localStorage.setItem('checkoutItems', JSON.stringify(selectedItems));
    
    // 跳转到结算页面
    window.location.href = './checkout.html';
}

// 检查购物车是否为空
function checkEmptyCart() {
    const cartTableContainer = document.querySelector('.cart-table-container');
    const emptyCart = document.querySelector('.empty-cart');
    const cartFooter = document.querySelector('.cart-footer');
    
    if (carList.length === 0) {
        if (cartTableContainer) cartTableContainer.style.display = 'none';
        if (emptyCart) emptyCart.style.display = 'flex';
        if (cartFooter) cartFooter.style.display = 'none';
    } else {
        if (cartTableContainer) cartTableContainer.style.display = 'block';
        if (emptyCart) emptyCart.style.display = 'none';
        if (cartFooter) cartFooter.style.display = 'flex';
    }
}

// 添加到购物车（用于推荐图书）
function addToCartFromRecommended(bookId) {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 显示登录弹窗
        document.getElementById('mask').style.display = 'flex';
        return;
    }
    
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        ApiService.cart.addToCart(bookId, 1)
            .then(response => {
                layer.close(loadingIndex);
                
                if (response.data) {
                    layer.msg('添加到购物车成功', {icon: 1});
                    
                    // 更新头部购物车数量
                    if (AuthService.updateCartCount) {
                        AuthService.updateCartCount();
                    }
                    
                    // 重新加载购物车数据
                    loadCartData();
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("添加到购物车失败:", error);
                layer.msg('添加到购物车失败，请重试', {icon: 2});
            });
    });
}

// 加载推荐图书
function loadRecommendedBooks() {
    // 获取用户信息
    const userInfo = AuthService.getUserInfo();
    const userId = userInfo ? userInfo.userId : null;
    
    // 调用API获取推荐图书
    ApiService.book.getYouMayLikeBooks(userId)
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderRecommendedBooks(response.data);
            } else {
                // 如果没有个性化推荐，获取热门图书
                ApiService.book.getHotBooks(10)
                    .then(hotResponse => {
                        renderRecommendedBooks(hotResponse.data);
                    })
                    .catch(error => {
                        console.error('获取热门图书失败:', error);
                    });
            }
        })
        .catch(error => {
            console.error('获取推荐图书失败:', error);
            // 出错时获取热门图书作为备选
            ApiService.book.getHotBooks(10)
                .then(hotResponse => {
                    renderRecommendedBooks(hotResponse.data);
                })
                .catch(hotError => {
                    console.error('获取热门图书失败:', hotError);
                });
        });
}

// 渲染推荐图书
function renderRecommendedBooks(books) {
    const bookList = document.querySelector('.book-list');
    bookList.innerHTML = ''; // 清空现有内容
    
    // 限制最多显示10本书
    const booksToShow = books.slice(0, 10);
    
    booksToShow.forEach(book => {
        const bookItem = document.createElement('div');
        bookItem.className = 'bookItem';
        bookItem.innerHTML = `
            <div class="book-image">
                <a href="detail.html?id=${book.id}">
                    <img src="${book.imageUrl || './img/default-book.jpg'}" alt="${book.title}">
                </a>
            </div>
            <div class="book-info">
                <h4 class="book-title">
                    <a href="detail.html?id=${book.id}">${book.title}</a>
                </h4>
                <div class="book-meta">
                    <span class="book-condition">${book.degree || '未知'}</span>
                    <span class="book-age">${book.ageRange || '适合各年龄段'}</span>
                </div>
                <div class="book-price">¥${book.price}</div>
            </div>
        `;
        
        // 添加点击事件
        bookItem.addEventListener('click', function() {
            window.location.href = `detail.html?id=${book.id}`;
        });
        
        bookList.appendChild(bookItem);
    });
    
    // 如果书籍数量不足10本，添加空白项
    if (booksToShow.length < 10) {
        for (let i = booksToShow.length; i < 10; i++) {
            const emptyItem = document.createElement('div');
            emptyItem.className = 'bookItem empty';
            bookList.appendChild(emptyItem);
        }
    }
}
                    